package com.example.application4.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.application4.R;
import com.example.application4.adapter.UserAdapter;
import com.example.application4.database.UserDAO;
import com.example.application4.pojo.User;

import java.util.ArrayList;
import java.util.List;

public class FriendListActivity extends AppCompatActivity {

    private ListView listView;
    private UserAdapter adapter;
    private UserDAO userDAO;
    private Button btnPrevPage, btnNextPage;
    private Spinner spinnerPage;
    private TextView tvPageInfo;

    private int currentPage = 1;
    private static final int USERS_PER_PAGE = 10;
    private int totalPages = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_list); // 设置布局

        // 初始化控件
        listView = findViewById(R.id.listViewFriends); // 获取 ListView 控件
        btnPrevPage = findViewById(R.id.btnPrevPage); // 获取上一页按钮
        btnNextPage = findViewById(R.id.btnNextPage); // 获取下一页按钮
        spinnerPage = findViewById(R.id.spinnerPage); // 获取页面选择器
        tvPageInfo = findViewById(R.id.tvPageInfo); // 获取页码信息文本

        userDAO = new UserDAO(this); // 创建 UserDAO 对象，用于数据库操作

        // 获取当前用户的用户名
        String currentUsername = getSharedPreferences("appPreferences", MODE_PRIVATE).getString("username", "");

        // 计算总页数
        int totalUsers = userDAO.getTotalUsersExceptCurrent(currentUsername);
        totalPages = (int) Math.ceil((double) totalUsers / USERS_PER_PAGE);

        // 初始加载第一页数据
        loadUsers(currentUsername, currentPage, USERS_PER_PAGE);

        // 上一页按钮点击事件
        btnPrevPage.setOnClickListener(v -> {
            if (currentPage > 1) {
                currentPage--;
                loadUsers(currentUsername, currentPage, USERS_PER_PAGE);
            }
        });

        // 下一页按钮点击事件
        btnNextPage.setOnClickListener(v -> {
            if (currentPage < totalPages) {
                currentPage++;
                loadUsers(currentUsername, currentPage, USERS_PER_PAGE);
            }
        });

        // 页面选择器点击事件
        spinnerPage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentPage = position + 1;
                loadUsers(currentUsername, currentPage, USERS_PER_PAGE);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 无操作
            }
        });

        // ListView 的点击事件
        listView.setOnItemClickListener((parent, view, position, id) -> {
            User user = (User) parent.getItemAtPosition(position);
            showUserDetail(user);
        });
    }

    private void showUserDetail(User user) {
        // 创建对话框构建器
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 加载对话框布局
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_user, null);
        // 获取对话框中的控件
        TextView textViewName = dialogView.findViewById(R.id.tvUsername);
        TextView textViewEmail = dialogView.findViewById(R.id.tvEmail);
        Button buttonClose = dialogView.findViewById(R.id.btnClose);
        Button buttonFollow = dialogView.findViewById(R.id.btnFollow);

        // 设置对话框内容
        textViewName.setText("用户名: " + user.getUsername());
        textViewEmail.setText("电子邮箱: " + user.getEmail());

        // 设置对话框视图
        builder.setView(dialogView);
        Dialog dialog = builder.show();

        // 关闭按钮点击事件
        buttonClose.setOnClickListener(v -> {
            dialog.dismiss();
        });

        // 关注按钮点击事件
        buttonFollow.setOnClickListener(v -> {
            Toast.makeText(this, "关注成功 " + user.getUsername(), Toast.LENGTH_SHORT).show();
        });
    }

    private void loadUsers(String currentUsername, int page, int limit) {
        // 在新线程中加载用户数据
        new Thread(() -> {
            List<User> userList = userDAO.getUsersExceptCurrentWithPagination(currentUsername, (page - 1) * limit, limit);

            // 更新 UI 需要在主线程中进行
            new Handler(Looper.getMainLooper()).post(() -> {
                if (adapter == null) {
                    // 如果适配器不存在，创建新的适配器
                    adapter = new UserAdapter(FriendListActivity.this, userList);
                    listView.setAdapter(adapter);
                } else {
                    // 如果适配器已存在，更新适配器数据
                    adapter.clear();
                    adapter.addAll(userList);
                    adapter.notifyDataSetChanged();
                }

                // 更新分页控件
                updatePageControls(page);
            });
        }).start();
    }

    private void updatePageControls(int page) {
        currentPage = page;

        // 生成页码列表
        List<String> pages = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pages.add("第" + i + "页");
        }

        // 创建页码选择器的适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, pages);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerPage.setAdapter(adapter);

        // 设置当前选中的页码
        spinnerPage.setSelection(currentPage - 1);

        // 更新页码信息文本
        tvPageInfo.setText(currentPage + " / " + totalPages);

        // 更新上一页和下一页按钮的状态
        btnPrevPage.setEnabled(currentPage > 1);
        btnNextPage.setEnabled(currentPage < totalPages);
    }
}